#include "player.h"
#include <sys/time.h>

Player::Player(string TeamName) : Person()
{ 
    teamName=TeamName;
    ss<<"(init "<<teamName <<") "<<endl;
    sock << ss.str();
    ss.str(string());
    string response;
    sock >> response;
    //   cout << response <<endl;
    sock.setReceiverAdress();

    timelast=0;
}


void Player::destroy()//(bye)
{
    sock << "(bye)\n";
}

void Player:: kicktogoal()
{
    Player::get_status();
    int kickangle= parser.goal_r[1];
    int kickforce= parser.goal_r[0] * 100;
    if (kickforce>100)
        kickforce=100;

    Player::follow_ball(kickforce,kickangle);
}

void Player::follow_ball(int kickangle, int kickforce) 
{
    static int arg=0,ang=0;
    moment=2;

    Player::get_status();

    arg= parser.ball[0];
    ang= parser.ball[1];

    velocity=20*arg;

    if(velocity>100)
        velocity=100;
    
    if(parser.objectball)
    {
        if (ang > 3)
        {
            Player::turn(moment);
        }
        if (ang<-3)
        {
            Player::turn(-moment);
        }
        if (arg>0)
        {
            Player::run(velocity);

        }
        if (arg <1 && ang<10 && ang>-10)
        {
            Player::kick(kickangle,kickforce);
           // Player::kick(kickangle,kickforce);
        }
    }

    if (parser.objectball==false )
    {
        Player::turn(3);
    }
}

void Player::run(double power) //(dash power)
{
    ss.str(string());
    ss << "(dash "<< power <<")"<<endl;
    sock<<ss.str();
}

//void Player::pass(); PASAR

void Player::kick(int power,int direction) //(kick Power Direction)
{
    ss.str(string());
    ss << "(kick "<< power <<" "<< direction<<")"<<endl;
    sock<<ss.str();

}

void Player::ballHandling()
{

}

void Player::turn(int moment) //(turn Moment)
{   ss.str(string());
    ss << "(turn "<< moment <<")"<<endl;
    sock<<ss.str();
}

void Player::turn_neck(int angle) //(turn_neck Angle)
{
    ss.str(string());
    ss << "(turn_neck "<< angle <<")"<<endl;
    sock<<ss.str();
}

//void Player::dribble();//¿REGATEAR?

void Player::move(int x, int y) // (move x y)
{
    ss.str(string());
    ss << "(move "<< x <<" "<< y <<")"<<endl;
    sock<<ss.str();
}

void Player::catch_dir(int dir)//(catch Direction)
{
    ss << "(catch "<< dir <<")"<<endl;
}

void Player::yell(string message)//(say Message)
{
    ss << "(say "<< message<<")"<<endl;
}

void Player::see()
{
}

void Player::listen()
{
}

void Player::handle_state()
{
    ss.str(string());
    Player::get_status();
    ss <<cont.select_state();  
    cout <<ss.str(); 
   // sock<<ss.str();
   // ss.str(string());
}

void Player::get_status() //with this, we can get both body and see sensors (until now, just the ball detection is implemented)
{
    string buffer;
    sock>>buffer;
   // cout << "Buffer (get status): "<<  buffer<< endl;
    parser.parse(buffer);
}


